<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import CreateOrder from "./components/CreateOrder.vue";
import CreateGo from "./components/CreateGo.vue";
import CostDialog from "./components/CostDialog.vue";
import CompleteDialog from "./components/CompleteHandle.vue";
import PlanDialog from "./components/PlanHandle.vue";
import {
  getWarehousingList,
  warehouseOut,
  temporaryStorage,
  importExcel,
  getCargoServiceList,
  delCheckinTasks,
  delCheckinSubTasks,
  getCheckoutList
} from "/@/api/warehousing";
import { getUserList } from "/@/api/user";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { readExcel } from "/@/utils/index";
import * as XLSX from "xlsx";
import { loadEnv } from "@build/index";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
dayjs.extend(utc);
dayjs.extend(timezone);
const { VITE_PROXY_DOMAIN_REAL } = loadEnv();

defineOptions({
  name: "WarehousingIndex"
});

onMounted(() => {
  getTableData();
});

const tableData = ref([]);
const query = reactive({
  currentPage: 1,
  pageSize: 15,
  type: 0,
  is_ex_warehouse: 0
});
const total = ref(0);
const dialogVisible = ref<boolean>(false);
const goDialogVisible = ref<boolean>(false);
const whiteList = ["admin", "super", "warehouse"];
const role = JSON.parse(localStorage.getItem("authorized-token")).role; // 角色
const isAdmin = whiteList.includes(role);
const routerName = useRouter().currentRoute.value.name;
let btnAuth = [];
const userList = ref([]);
const formData = ref({
  user_name: "",
  user_nid: null,
  type: null, // 类型 1-提柜，2-中转，3-退件
  container_no: "", // 柜号
  bill_of_lading: "", // 提单号
  shipping_company: "",
  estimated_time: "",
  notes: "", // 备注
  service: []
});
const title = ref("");
const goTitle = ref("");
const goFormData = ref({
  task_identifier: "", //	String	父identifier
  checkout_name: "", //	String	出库方式名
  place_to_go: "", //	String	去向
  box_no: "", //	String	箱麦
  quantity: "", //	String	数量
  total_volume: "", //	String	总体积，保留两位小数
  weight: "", //	String	重量
  length: "", //	String	箱长，一般箱长 * 箱宽 * 箱高 = 总体积，保留两位小数
  width: "", //	String	箱宽，保留两位小数
  height: "", //	String	箱高，保留两位小数
  ship_to_address: "", //	String	收货地址
  fba_id: "", //	String	FBA ID
  ref_id: "", //	String	Ref ID
  is_temporary_storage: 0, // 是否暂扣 0 否 1 是
  fee: "0.00", // 费用，保留两位小数
  notes: "" //	String	备注
});
const multipleSelection = ref([]);
const costDialogVisible = ref(false);
const costFormData = ref({
  id: "",
  fee: ""
});
const completeDialogVisible = ref(false);
const completeFormData = ref({
  id: "",
  completion_time: ""
});
const planDialogVisible = ref(false);
const planFormData = ref({
  id: "",
  planning_time: ""
});
const expands = ref([]);
const createOrderRef = ref(null);
const checkoutList = ref([]);

/**根据不同路由设置查询条件 */
const setQueryType = () => {
  if (routerName === "DeliveryListIndex") {
    query.type = 0;
    query.is_ex_warehouse = 1;
  }
  if (routerName === "WarehousingIndex") {
    query.type = 0;
  } else if (routerName === "TackTransfer") {
    query.type = 2;
  } else if (routerName === "TackLiftingCabinet") {
    query.type = 1;
  } else if (routerName === "TackReturn") {
    query.type = 3;
  }
};
setQueryType();

/** 设置按钮权限 */
const setBtnAuth = () => {
  if (isAdmin) {
    if (routerName === "DeliveryListIndex") {
      btnAuth = [
        "修改",
        "添加费用",
        "完成",
        "添加规划时间",
        "Excel导出",
        "暂扣"
      ];
    } else if (routerName === "WarehousingIndex") {
      btnAuth = ["出库", "修改", "添加去向", "暂扣", "删除"];
    } else if (routerName === "TackTransfer") {
      btnAuth = ["出库", "修改", "添加去向", "暂扣"];
    } else if (routerName === "TackLiftingCabinet") {
      btnAuth = ["出库", "修改", "添加去向", "暂扣"];
    } else if (routerName === "TackReturn") {
      btnAuth = ["出库", "修改", "添加去向", "暂扣"];
    }
  } else {
    if (routerName === "DeliveryListIndex") {
      btnAuth = [];
    } else if (routerName === "WarehousingIndex") {
      btnAuth = ["修改", "添加去向", "删除"];
    } else if (routerName === "TackTransfer") {
      btnAuth = ["修改", "添加去向"];
    } else if (routerName === "TackLiftingCabinet") {
      btnAuth = ["修改", "添加去向"];
    } else if (routerName === "TackReturn") {
      btnAuth = ["修改", "添加去向"];
    }
  }
};
setBtnAuth();

/** 获取表格数据 */
const getTableData = () => {
  getWarehousingList(query).then((res: any) => {
    const ary = Object.values(res.data.data);
    ary.forEach((item: any) => {
      if (!Object.prototype.hasOwnProperty.call(item, "service"))
        item.service = [];
    });
    tableData.value = ary;
    total.value = res.data.total;
  });
};

/** 获取用户下拉 */
const getUserData = () => {
  if (isAdmin) {
    getUserList().then(({ data }) => {
      userList.value = data;
      createOrderRef.value.serviceForm.userNid = data[0].nid;
    });
  }
};
const getCheckoutData = () => {
  getCheckoutList().then(({ data }) => {
    checkoutList.value = data;
  });
};

/** 弹窗完成按钮 接口成功的回调 */
const createSuccess = () => {
  dialogVisible.value = false;
  goDialogVisible.value = false;
  getTableData();
};

/** 调整每页大小的回调 */
const handleSizeChange = val => {
  query.pageSize = val;
  getTableData();
};

/** 页数回调 */
const handleCurrentChange = val => {
  query.currentPage = val;
  getTableData();
};

/** 创建入库清单 */
const createHandle = () => {
  getUserData();
  formData.value = {
    user_name: "",
    user_nid: null,
    type: null, // 类型 1-提柜，2-中转，3-退件
    container_no: "", // 柜号
    bill_of_lading: "", // 提单号
    shipping_company: "",
    estimated_time: "",
    notes: "", // 备注
    service: []
  };
  routerName === "DeliveryListIndex"
    ? (title.value = "创建出库清单")
    : (title.value = "创建入库清单");
  dialogVisible.value = true;
};

/** 修改入库清单 */
const editOrder = val => {
  getCargoServiceList({ identifier: val.identifier }).then(({ data }) => {
    const obj = { ...val };
    obj.service = data;
    obj.estimated_time = obj.estimated_time
      ? dayjs(obj.estimated_time * 1000).format("YYYY-MM-DD HH:mm:ss")
      : "";
    formData.value = obj;
    routerName === "DeliveryListIndex"
      ? (title.value = "修改出库清单")
      : (title.value = "修改入库清单");
    dialogVisible.value = true;
  });
};

/** 过滤类型 */
const filterType = val => {
  if (val === 1) {
    return "提柜";
  } else if (val === 2) {
    return "中转";
  } else {
    return "退件";
  }
};

/** 出库 */
const issueHandle = ({ user_nid, identifier }) => {
  ElMessageBox.confirm("是否确定出库?", "提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning"
  })
    .then(() => {
      warehouseOut({ user_nid, identifier }).then(() => {
        ElMessage({
          type: "success",
          message: "操作成功"
        });
        getTableData();
      });
    })
    .catch(() => {});
};

/** 新增去向 */
const addGo = val => {
  getCheckoutData();
  goFormData.value = {
    task_identifier: val, //	String	父identifier
    checkout_name: "", //	String	出库方式名
    place_to_go: "", //	String	去向
    box_no: "", //	String	箱麦
    quantity: "", //	String	数量
    total_volume: "", //	String	总体积，保留两位小数
    weight: "", //	String	重量
    length: "", //	String	箱长，一般箱长 * 箱宽 * 箱高 = 总体积，保留两位小数
    width: "", //	String	箱宽，保留两位小数
    height: "", //	String	箱高，保留两位小数
    ship_to_address: "", //	String	收货地址
    fba_id: "", //	String	FBA ID
    ref_id: "", //	String	Ref ID
    is_temporary_storage: 0, // 是否暂扣 0 否 1 是
    fee: "0.00", // 费用，保留两位小数
    notes: "" //	String	备注
  };
  goDialogVisible.value = true;
  goTitle.value = "添加去向";
};

/** 修改去向 */
const editGo = ({
  task_identifier,
  checkout_name,
  place_to_go,
  box_no,
  quantity,
  total_volume,
  weight,
  length,
  width,
  height,
  ship_to_address,
  fba_id,
  ref_id
}) => {
  getCheckoutData();
  goFormData.value = {
    task_identifier,
    checkout_name,
    place_to_go,
    box_no,
    quantity,
    total_volume,
    weight,
    length,
    width,
    height,
    ship_to_address,
    fba_id,
    ref_id,
    is_temporary_storage: 0,
    fee: "0.00",
    notes: ""
  };
  goDialogVisible.value = true;
  goTitle.value = "修改去向";
};

/** 暂扣 */
const withhold = (
  id: Number,
  is_temporary_storage: Number,
  identifier: String
) => {
  let message = "是否暂扣此暂扣?";
  if (is_temporary_storage == 0) {
    message = "是否取消此暂扣?";
  }
  ElMessageBox.confirm(message, "提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning"
  })
    .then(() => {
      temporaryStorage({
        id,
        is_temporary_storage,
        identifier,
        data_sources: query.is_ex_warehouse
      }).then(() => {
        ElMessage({
          type: "success",
          message: "操作成功"
        });
        getTableData();
      });
    })
    .catch(() => {});
};

/** 选择表格的回调 */
const handleSelectionChange = val => {
  multipleSelection.value = val;
};

/** 添加费用 */
const costHandle = ({ id, fee }) => {
  costFormData.value = { id, fee };
  costDialogVisible.value = true;
};

/** 完成 */
const completionHandle = ({ id, completion_time }) => {
  completeFormData.value = {
    id,
    completion_time: completion_time
  };
  completeDialogVisible.value = true;
};

/** 添加规划时间 */
const addPlanTime = ({ id, planning_time }) => {
  planFormData.value = {
    id,
    planning_time: planning_time
  };
  planDialogVisible.value = true;
};

const readXlsx = file => {
  readExcel(file.raw, importExcelFn);
};

const importExcelFn = workbook => {
  let insertData = {
    user_name: "",
    container_no: "",
    bill_of_lading: "",
    notes: "",
    estimated_time: "",
    shipping_company: "",
    type: 1,
    boxs: []
  };
  let worksheet = workbook.Sheets[workbook.SheetNames[0]];
  const data = XLSX.utils.sheet_to_csv(worksheet, { FS: "\t" });
  let d = data.split("||");
  console.log(d);
  let i: any;
  for (i in d) {
    if (i > 1) {
      let value = d[i].split("\t");
      if (i == 2) {
        insertData.user_name = value[1];
        insertData.container_no = value[5];
        insertData.bill_of_lading = value[7];
        insertData.notes = value[9];
      } else if (i == 3) {
        insertData.estimated_time =
          value[1] != "" ? dayjs(value[1]).format("YYYY-MM-DD") : "";
        insertData.shipping_company = value[5];
        if (value[7] == "提柜") {
          insertData.type = 1;
        } else if (value[7] == "中转") {
          insertData.type = 2;
        } else if (value[7] == "退件") {
          insertData.type = 3;
        }
      } else if (i >= 5) {
        if (value[0] != "") {
          insertData.boxs.push({
            place_to_go: value[0],
            box_no: value[1],
            quantity: value[2],
            total_volume: value[3],
            weight: value[4],
            fba_id: value[5],
            ref_id: value[6],
            ship_to_address: value[7],
            checkout_name: value[8],
            notes: value[9]
          });
        }
      }
    }
  }
  importExcel(insertData).then(() => {
    ElMessage({
      type: "success",
      message: "操作成功"
    });
    getTableData();
  });
};
const downloadExcel = identifier => {
  let path =
    VITE_PROXY_DOMAIN_REAL +
    "/v1/download_warehouse_excel?identifier=" +
    identifier;
  window.location.href = path;
};
const downloadExampleExcel = () => {
  let path = "./Excel导入格式.xlsx";
  window.location.href = path;
};

/** 展开行的回调 */
const expandChange = (row, expandList) => {
  expands.value = expandList.map(item => item.id);
};

const deleteOeder = ({ identifier }) => {
  ElMessageBox.confirm("是否删除?", "提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning"
  }).then(() => {
    delCheckinTasks({ identifier }).then(() => {
      ElMessage({
        type: "success",
        message: "操作成功"
      });
      getTableData();
    });
  });
};

const deleteSubOeder = ({ id }) => {
  ElMessageBox.confirm("是否删除?", "提示", {
    confirmButtonText: "确 定",
    cancelButtonText: "取 消",
    type: "warning"
  }).then(() => {
    delCheckinSubTasks({ id }).then(() => {
      ElMessage({
        type: "success",
        message: "操作成功"
      });
      getTableData();
    });
  });
};
</script>

<template>
  <div class="warehousing-list">
    <el-card>
      <template v-if="query.type === 0 && query.is_ex_warehouse === 0">
        <el-button type="primary" @click="createHandle">创建入库清单</el-button>
        <el-upload
          :limit="1"
          :auto-upload="false"
          :on-change="readXlsx"
          style="margin-top: 10px"
        >
          <el-button type="primary">Excel导入</el-button>
          <el-button link type="primary" @click="downloadExampleExcel"
            >Excel导入格式</el-button
          >
        </el-upload>
      </template>
      <!-- <el-button
        type="primary"
        @click="generateExcel"
        v-if="query.is_ex_warehouse === 1"
        >excel导出</el-button
      > -->

      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%; margin-top: 20px"
        row-key="id"
        :expand-row-keys="expands"
        @selection-change="handleSelectionChange"
        @expand-change="expandChange"
      >
        <!-- <el-table-column
          v-if="query.is_ex_warehouse === 1"
          type="selection"
          width="55"
        /> -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <div style="padding-left: 20px">
              <el-table :data="row.subtasks" size="small">
                <el-table-column prop="place_to_go" label="去向" />
                <el-table-column prop="box_no" label="箱麦" />
                <el-table-column prop="task_identifier" label="柜号" />
                <el-table-column prop="checkout_name" label="出库方式" />
                <el-table-column prop="quantity" label="数量" />
                <el-table-column prop="total_volume" label="总体积" />
                <el-table-column prop="weight" label="重量" />
                <el-table-column prop="length" label="箱长" />
                <el-table-column prop="width" label="箱宽" />
                <el-table-column prop="height" label="箱高" />
                <el-table-column prop="ship_to_address" label="收货地址" />
                <el-table-column prop="fba_id" label="FBA ID" />
                <el-table-column prop="ref_id" label="Fef ID" />
                <el-table-column prop="fee" label="费用" />
                <el-table-column prop="is_temporary_storage" label="是否暂扣">
                  <template #default="{ row }">{{
                    row.is_temporary_storage ? "是" : "否"
                  }}</template>
                </el-table-column>
                <el-table-column prop="notes" label="备注" />
                <template v-if="query.is_ex_warehouse === 1">
                  <el-table-column prop="planning_time" label="规划时间">
                    <template #default="{ row }">
                      {{
                        row.planning_time
                          ? dayjs(row.planning_time * 1000)
                              .tz("America/Los_Angeles")
                              .format("YYYY-MM-DD")
                          : ""
                      }}
                    </template>
                  </el-table-column>
                </template>
                <el-table-column prop="completion_time" label="完成时间">
                  <template #default="{ row }">
                    {{
                      row.completion_time
                        ? dayjs(row.completion_time * 1000)
                            .tz("America/Los_Angeles")
                            .format("YYYY-MM-DD")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="创建时间(加利福尼亚)">
                  <template #default="{ row }">
                    {{
                      row.created_at
                        ? dayjs(row.created_at * 1000)
                            .tz("America/Los_Angeles")
                            .format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="更新时间(加利福尼亚)">
                  <template #default="{ row }">
                    {{
                      row.updated_at
                        ? dayjs(row.updated_at * 1000)
                            .tz("America/Los_Angeles")
                            .format("YYYY-MM-DD HH:mm:ss")
                        : ""
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  fixed="right"
                  width="120"
                  v-if="btnAuth.length"
                >
                  <template #default="{ row }">
                    <el-button
                      v-if="
                        btnAuth.includes('暂扣') &&
                        row.status !== 3 &&
                        row.is_temporary_storage == 0
                      "
                      size="small"
                      type="primary"
                      link
                      @click="withhold(row.id, 1, row.task_identifier)"
                      >暂扣</el-button
                    >
                    <el-button
                      v-if="
                        btnAuth.includes('暂扣') &&
                        row.status !== 3 &&
                        row.is_temporary_storage == 1
                      "
                      size="small"
                      type="primary"
                      link
                      @click="withhold(row.id, 0, row.task_identifier)"
                      >取消暂扣</el-button
                    >
                    <el-button
                      v-if="row.status !== 3"
                      size="small"
                      type="primary"
                      link
                      @click="editGo(row)"
                      >修改</el-button
                    >
                    <el-button
                      v-if="
                        query.is_ex_warehouse === 1 &&
                        btnAuth.includes('添加费用')
                      "
                      size="small"
                      type="primary"
                      link
                      @click="costHandle(row)"
                      >添加费用</el-button
                    >
                    <el-button
                      v-if="
                        query.is_ex_warehouse === 1 &&
                        btnAuth.includes('完成') &&
                        row.status !== 3
                      "
                      size="small"
                      type="primary"
                      link
                      @click="completionHandle(row)"
                      >完成</el-button
                    >
                    <el-button
                      v-if="btnAuth.includes('删除')"
                      size="small"
                      @click="deleteSubOeder(row)"
                      link
                      type="primary"
                      >删除</el-button
                    >
                    <el-button
                      v-if="
                        query.is_ex_warehouse === 1 &&
                        btnAuth.includes('添加规划时间')
                      "
                      size="small"
                      type="primary"
                      link
                      @click="addPlanTime(row)"
                      >添加规划时间</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="identifier" label="编号" width="80" />
        <el-table-column prop="user_name" label="客户名称" />
        <el-table-column label="类型">
          <template #default="{ row }">
            {{ filterType(row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="container_no" label="柜号" />
        <el-table-column prop="bill_of_lading" label="提单号" />
        <el-table-column prop="shipping_company" label="船司" />
        <el-table-column prop="notes" label="备注" />
        <el-table-column prop="estimated_time" label="预计到柜时间" width="120">
          <template #default="{ row }">
            {{
              row.estimated_time
                ? dayjs(row.estimated_time * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间(加利福尼亚)" width="120">
          <template #default="{ row }">
            {{
              row.created_at
                ? dayjs(row.created_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间(加利福尼亚)" width="120">
          <template #default="{ row }">
            {{
              row.updated_at
                ? dayjs(row.updated_at * 1000)
                    .tz("America/Los_Angeles")
                    .format("YYYY-MM-DD HH:mm:ss")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" v-if="btnAuth.length">
          <template #default="{ row }">
            <el-button
              style="margin-bottom: 5px"
              type="primary"
              size="small"
              @click="issueHandle(row)"
              v-if="query.is_ex_warehouse === 0 && btnAuth.includes('出库')"
              >出库</el-button
            >
            <el-button
              style="margin-bottom: 5px"
              v-if="btnAuth.includes('修改')"
              type="primary"
              size="small"
              @click="editOrder(row)"
              >修改</el-button
            >
            <el-button
              v-if="btnAuth.includes('删除')"
              size="small"
              @click="deleteOeder(row)"
              style="margin-bottom: 5px"
              >删除</el-button
            >
            <el-button
              style="margin-bottom: 5px"
              v-if="query.is_ex_warehouse === 0 && btnAuth.includes('添加去向')"
              type="primary"
              size="small"
              @click="addGo(row.identifier)"
              >添加去向</el-button
            >
            <el-button
              style="margin-bottom: 5px"
              v-if="btnAuth.includes('Excel导出')"
              size="small"
              type="primary"
              @click="downloadExcel(row.identifier)"
              >Excel导出</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          :page-sizes="[5, 10, 15, 20, 30]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="Number(total)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <create-order
        ref="createOrderRef"
        v-model="dialogVisible"
        :is-admin="isAdmin"
        :user-list="userList"
        :form-data="formData"
        :title="title"
        @submit-success="createSuccess"
      />

      <create-go
        v-model="goDialogVisible"
        :form-data="goFormData"
        :title="goTitle"
        :checkout-list="checkoutList"
        @submit-success="createSuccess"
      />

      <cost-dialog
        v-model="costDialogVisible"
        :form-data="costFormData"
        @submit-success="createSuccess"
      />

      <complete-dialog
        v-model="completeDialogVisible"
        :form-data="completeFormData"
        @submit-success="createSuccess"
      />

      <plan-dialog
        v-model="planDialogVisible"
        :form-data="planFormData"
        @submit-success="createSuccess"
      />
    </el-card>
  </div>
</template>
